package cc.fs.zhihuapp.utils;

import android.content.Context;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Objects;

import cc.fs.zhihuapp.App;

/**
 * Created by fostion on 2015/9/6.
 */
public class Cache {
    private static Kryo kryo = new Kryo();

    public static void write(String fileName, Object obj) {
        try {
            FileOutputStream fo = App.instance.openFileOutput(fileName, Context.MODE_PRIVATE);
            Output output = new Output(fo);

            kryo.writeObject(output, obj);
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <E>E read(String fileName,  Class<E> c) {
        E rlt = null;
        try {
            FileInputStream fi = App.instance.openFileInput(fileName);
            Input input = new Input(fi);
            rlt = kryo.readObject(input, c);
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rlt;
    }

    public static void rm(String fileName) {
        App.instance.deleteFile(fileName);
    }

    public static void clear() {
        File toDelete = new File("/data/data/" + App.instance.getPackageName() + "/files");
        if (toDelete != null && toDelete.exists() && toDelete.isDirectory()) {
            for(File item : toDelete.listFiles()){
                item.delete();
            }
        }
    }

    public static void set(String fileName, Object obj) {
        if (obj != null) {
            write(fileName, obj);
        } else {
            rm(fileName);
        }
    }

    public static <T>T get(String fileName, Class<T> c){
        return read(fileName,c);
    }

}
